package com.axinfu.util.http.response;

import com.axinfu.util.EmptyUtil;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.util.EntityUtils;

/**
 * HttpResponseHandler
 *
 * @author zjn
 * @since 2022/3/23
 */
public class ByteResponseHandler implements ResponseHandler<HttpResponseResult> {

    private HttpResponseResult httpResponseResult;

    public ByteResponseHandler() {
    }

    /**
     * response处理程序
     *
     * @param request  request
     * @param response response
     * @return 处理后结果
     * @throws Exception 异常
     */
    @Override
    public HttpResponseResult handler(HttpUriRequest request, HttpResponse response) throws Exception {
        byte[] responseByte = null;
        HttpEntity respEntity = response.getEntity();
        if (EmptyUtil.isNotEmpty(respEntity)) {
            responseByte = EntityUtils.toByteArray(response.getEntity());
        }
        httpResponseResult = new HttpResponseResult(responseByte);
        httpResponseResult.setStatus(response.getStatusLine().getStatusCode());
        Header[] headers = response.getAllHeaders();
        if (headers != null && headers.length > 0) {
            for (Header header : headers) {
                httpResponseResult.addHeader(header.getName(), header.getValue());
            }
        }
        return httpResponseResult;
    }

    @Override
    public String buildPrintBody() {
        return "B]" + httpResponseResult.getResponseByte().length;
    }
}
